#!/usr/bin/python

#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
#    This file is part of ICTP RegCM.
#    
#    Use of this source code is governed by an MIT-style license that can
#    be found in the LICENSE file or at
#
#         https://opensource.org/licenses/MIT.
#
#    ICTP RegCM is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

# Script that evaluates differences between different
# initial conditions for RegCM v3-v4 and produces
# png images of the GrADS plots by M. Scarcia

# !!! Now working only for 1 month simulations !!!

import os,sys,subprocess
from optparse import OptionParser

class MyOptions(object):
    def __init__(self):
        usage = "usage: %s [-q] [-c|-d directory] " % sys.argv[0]
        self.parser = OptionParser(usage)
        self.parser.add_option("-n","--name",dest="domain",default="MyDomain",
                      help="Domain name (as in regcm.in)")
        self.parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose", default=True,
                      help="Don't print status messages to stdout")
        self.parser.add_option("-d","--d1", dest="path1",default="./Input1",
                  help="Specify first ICBC files directory", metavar="DIR")
        self.parser.add_option("-f","--d2", dest="path2",default="./Input2",
                  help="Specify second ICBC files directory", metavar="DIR")


    def parse(self,args):
        
        # hardcoded date (for now)
        startdate="19890101"
        
        (self.options, self.args) = self.parser.parse_args(args=args)
        self.verbose=self.options.verbose
        self.domain = self.options.domain
        self.path1 = self.options.path1
        self.path2 = self.options.path2

        # Checks on input existence plus...
        # ...check for v3 naming scheme and replace with v4 scheme...

        # ...for the terrain file
        if not os.path.isfile(self.path1+self.domain+".CTL"):
            if os.path.isfile(self.path1+"DOMAIN.CTL"):
                os.rename(self.path1+"DOMAIN.CTL",self.path1+self.domain+".CTL")
            else:
                print "No terrain file in",self.path1,"found!"
                os.sys.exit(1)
        if not os.path.isfile(self.path2+self.domain+".CTL"):
            if os.path.isfile(self.path2+"DOMAIN.CTL"):
                os.rename(self.path2+"DOMAIN.CTL",self.path2+self.domain+".CTL")
            else:
                print "No terrain file in",self.path2,"found!"
                os.sys.exit(1)

        # ...for the ICBC file
        if not os.path.isfile(self.path1+self.domain+"_ICBC"+startdate+"00.CTL"):
            if os.path.isfile(self.path1+"ICBC"+startdate+"00.CTL"):
                os.rename(self.path1+"ICBC"+startdate+"00.CTL",self.path1+self.domain+"_ICBC"+startdate+"00.CTL")
            else:
                print "No valid terrain file in",self.path1,"found!"
                os.sys.exit(1)
        if not os.path.isfile(self.path2+self.domain+"_ICBC"+startdate+"00.CTL"):
            if os.path.isfile(self.path2+"ICBC"+startdate+"00.CTL"):
                os.rename(self.path2+"ICBC"+startdate+"00.CTL",self.path2+self.domain+"_ICBC"+startdate+"00.CTL")
            else:
                print "No valid terrain file in",self.path2,"found!"
                os.sys.exit(1)
        
def main():

    options = MyOptions()
    options.parse(sys.argv[1:])

    domain = options.domain
    path1 = options.path1
    path2 = options.path2

    # hardcoded date (for now)
    startdate="19890101"
        
    # Default scripts

    check_domain="""* Script generated by preproc-compare.py
    'open PATH1/DOMNAME.CTL'
    'open PATH2/DOMNAME.CTL'
    'htdm=abs(ht.1-ht.2)'
    'd htdm'
    'printim elev.png'
    """

    check_icbc="""* Script generated by preproc-compare.py
    'open PATH1/DOMNAME_ICBCDATE.CTL'
    'open PATH2/DOMNAME_ICBCDATE.CTL'
    'tdm=ave(abs(t.1-t.2),T=1,T=125)'
    'd tdm'
    'printim temp.png'
    'clear'
    'wdm=ave(abs(sqrt(u.1*u.1+v.1*v.1)-sqrt(u.2*u.2+v.2*v.2)),T=1,T=125)'
    'd wdm'
    'printim windmag.png'
    'clear'
    'qdm=ave(abs(q.1-q.2),T=1,T=125)'
    'd qdm'
    'printim moist.png'
    'clear'
    'pxdm=ave(abs(px.1-px.2),T=1,T=125)'
    'd pxdm'
    'printim press.png'
    'clear'
    'tsdm=ave(abs(ts.1-ts.2),T=1,T=125)'
    'd tsdm'
    'printim satemp.png'"""

    check_domain = check_domain.replace("PATH1",path1)
    check_domain = check_domain.replace("PATH2",path2)
    
    check_icbc = check_icbc.replace("PATH1",path1)
    check_icbc = check_icbc.replace("PATH2",path2)

    check_domain = check_domain.replace("DOMNAME",domain)
    check_icbc = check_icbc.replace("DOMNAME",domain)

    check_icbc = check_icbc.replace("DATE",startdate+"00")
    
    out1 = open("check-domain.gs","w")
    out1.write(check_domain)

    out2 = open("check-icbc.gs","w")
    out2.write(check_icbc)

    out1.close()
    out2.close()

    try :
        subprocess.call(["gradsc","-lbxc","check-domain.gs"])
    except OSError :
        print "No grads binary available!"
        os.sys.exit(1)
        
    try :
        subprocess.call(["gradsc","-lbxc","check-icbc.gs"])
    except OSError :
        print "No grads binary available!"
        os.sys.exit(1) 

    os.remove("check-domain.gs")
    os.remove("check-icbc.gs")

if __name__ == "__main__":
    main()
